import { Box, Button, Modal } from "@mui/material";
import { useState } from "react";
import { useLazyGetCommentsQuery } from "../../api/posts";
import { Loader } from "./loader";
import { CommentCard } from "./commentCard";

export const PostCard = ({ id, title, body, s }) => {
  const [data, setData] = useState(null);
  const [getComments, { isLoading, isError }] = useLazyGetCommentsQuery();

  const handleOpen = async () => {
    if (data) {
      setData(null);
    } else {
      try {
        const response = await getComments(id);
        setData(response.data);
      } catch (error) {
        alert("Error fetching surprise:", error);
      }
    }
  };

  return (
    <Box className={s.user__postcard}>
      <div className={s.user__postcard__title} onClick={() => handleOpen()}>
        {title}
      </div>
      <div className={s.user__postcard__body}>{body}</div>

      {data ? (
        <div className={s.user__postcard__comment}>
          <div className={s.user__postcard__comment__title}>Комментарии</div>

          {data.map((elem, key) => (
            <CommentCard
              key={key}
              name={elem.name}
              email={elem.email}
              body={elem.body}
              s={s}
            />
          ))}
        </div>
      ) : isLoading ? (
        <Loader width={"100px"} height={"100px"} />
      ) : null}
    </Box>
  );
};
